package com.sihai.core.beans;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;

public class BeanLocator {

    private BeanLocator() {
    }

    private static ApplicationContext applicationContext;

    /**
     * @param applicationContext spring ApplicationContext
     */
    public static void setApplicationContext(ApplicationContext applicationContext) {
        BeanLocator.applicationContext = applicationContext;
    }

    /**
     * 按照bean的名字获得bean引用
     *
     * @param name bean name
     * @return spring object
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }


    /**
     * 按照bean的名字并检查类型获得bean引用
     *
     * @param name bean name
     * @param type bean type
     * @return spring object
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name, Class<T> type) {
        return (T) applicationContext.getBean(name, type);
    }


    /**
     * 按照bean的类型获得bean引用
     *
     * @param type bean的类型
     * @return spring object
     */
    public static <T> T getBean(Class<T> type) {
        String[] beanNames = applicationContext.getBeanNamesForType(type);
        if (beanNames.length == 0) {
            throw new NoSuchBeanDefinitionException(type, "can not found any bean definition with type:[" + type + "]");
        }
        if (beanNames.length > 1) {
            throw new NoSuchBeanDefinitionException(type, "found more than one beans definition with type:[" + type + "]");
        }

        return getBean(beanNames[0], type);

    }

    /**
     * @return {@link org.springframework.context.ApplicationContext}
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
